package com.hankol.community.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.baselibrary.BaseConstant
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.*
import com.baselibrary.view.expandabletext.ExpandableTextView
import com.hankol.community.R
import com.hankol.community.bean.FollowDynamicBean
import com.hankol.community.bean.RecommendUserBean
import com.baselibrary.utils.ScalePageTransformer
import com.hankol.community.view.HotCommentsView
import com.hankol.community.viewmodel.CommunityViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import java.util.*


/**
 *@author:yuyang
 *2022/4/26
 *desc:关注页动态列表
 */
class FollowDynamicAdapter(var context: Context, var data: ArrayList<FollowDynamicBean.DataBeanX.DataBean>, var viewModel: CommunityViewModel) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private lateinit var mCallback: Callback
    var mCardLeakCall: OnRecommendCardLeakCall? = null
    var isVoice: Boolean = false

    companion object {
        const val TYPE_DYNAMIC = 0//动态
        const val TYPE_RECOMMEND = 1//没关注任何人下的推荐
        const val TYPE_INTEREST = 2//已有关注下的可能感兴趣
        const val TYPE_USER_LIST = 4//顶部列表
        const val RECOMMEND_EMPTY_INDEX = 1
        const val RECOMMEND_EMPTY_SIZE = 50
    }

    fun setCallback(mCallback: Callback) {
        this.mCallback = mCallback
    }

    interface OnRecommendCardLeakCall {
        fun onCardLeak(list: List<RecommendUserBean>)
    }

    interface Callback {
        fun onClickShare(position: Int, item: FollowDynamicBean.DataBeanX.DataBean)
        fun onClickComment(position: Int, item: FollowDynamicBean.DataBeanX.DataBean)
        fun onClickNoCare(userId: Int)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            TYPE_RECOMMEND -> {
                view = LayoutInflater.from(context).inflate(R.layout.item_recommend_users, parent, false)
                RecommendViewHolder(view)
            }
            TYPE_INTEREST -> {
                view = LayoutInflater.from(context).inflate(R.layout.item_interest_users, parent, false)
                InterestViewHolder(view, context, viewModel)
            }
            TYPE_USER_LIST -> {
                view = LayoutInflater.from(context).inflate(R.layout.layout_follow_head, parent, false)
                UserListViewHolder(view)
            }
            else -> {
                view = LayoutInflater.from(context).inflate(R.layout.item_follow_locus, parent, false)
                DynamicViewHolder(view, this)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        when (holder) {
            is RecommendViewHolder -> {
                var clickVpPos = -1
                holder.tvLocusTitle.paint.isFakeBoldText = true
                if (position == 1 && data.size == 2) {
                    holder.topView.visibility = View.GONE
                    holder.bottomView.visibility = View.GONE
                } else if (position == 2 && data.size == 3) {
                    holder.topView.visibility = View.VISIBLE
                    holder.bottomView.visibility = View.GONE
                } else if (position == 1 && data.size > 2) {
                    holder.topView.visibility = View.GONE
                    holder.bottomView.visibility = View.VISIBLE
                } else if (position == 2 && data.size > 2) {
                    holder.topView.visibility = View.VISIBLE
                    holder.bottomView.visibility = View.VISIBLE
                }
                if (!data[position].isHasFollowUser) {
                    //没有关注的人
                    holder.tvLocusTitle.text = "您还没有关注的人呢"
                    holder.tvLocusTime.text = "关注后，可以在这里查看对方的最新动态"
                } else {
                    holder.tvLocusTime.text = "去发现更多有趣的人吧"
                    holder.tvLocusTitle.text = "关注的人近期未发布动态"

                }
                holder.viewPager.pageMargin = ScreenUtils.dpToPx(14)
                val transformer = ScalePageTransformer(true)
                holder.viewPager.setPageTransformer(true, transformer)
                holder.viewPager.offscreenPageLimit = 3
                holder.viewPager.currentItem = 1
                val cardPagerAdapter = CardPagerAdapter(context, viewModel)
                cardPagerAdapter.mPagerViewList = data[position].recommendUserBeans
                cardPagerAdapter.setCallback(object : CardPagerAdapter.ClickCallback {
                    override fun onClickClose(userId: Int, i: Int) {
                        clickVpPos = i
                        mCallback.onClickNoCare(userId)
                        data[position].recommendUserBeans.removeAt(i)
                        holder.viewPager.adapter?.notifyDataSetChanged()
                        if (i < data[position].recommendUserBeans.size - 1) {
                            holder.viewPager.setCurrentItem(i + 1, true)
                        }
                    }

                    override fun onClickFocus(doFocus: Boolean, i: Int) {
                        data[position].recommendUserBeans[i].hasFocus = doFocus
                        if (doFocus) {
                            if (i < data[position].recommendUserBeans.size - 1) {
                                holder.viewPager.setCurrentItem(i + 1, true)
                            }
                        } else {
                            holder.viewPager.setCurrentItem(i, true)
                        }
                    }

                })
                holder.viewPager.adapter = cardPagerAdapter
                if (mCardLeakCall == null) {
                    mCardLeakCall = object : OnRecommendCardLeakCall {
                        override fun onCardLeak(list: List<RecommendUserBean>) {
                            data[position].recommendUserBeans.add(list[0])//添加到最后面
                            cardPagerAdapter.mPagerViewList = data[position].recommendUserBeans
                            holder.viewPager.adapter = cardPagerAdapter
                            holder.viewPager.setCurrentItem(clickVpPos, true)
                        }
                    }
                }
            }
            is InterestViewHolder -> {
                var adapter = RecommendUserAdapter(context as Activity, viewModel)
                holder.recyclerView.adapter = adapter
                adapter.setNewData(data[position].interestUserBeans)
            }
            is DynamicViewHolder -> {
                holder.setUI(context, data, position, viewModel, mCallback)
            }
            is UserListViewHolder -> {
                holder.setUI(data[position])
            }
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun getItemViewType(position: Int): Int {
        return data[position].itemType
    }

    class DynamicViewHolder(@NonNull itemView: View, var adapter: FollowDynamicAdapter) : RecyclerView.ViewHolder(itemView), AutoPlayItem {
        val rootView: RelativeLayout = itemView.findViewById(R.id.view_layout)
        val vipHeardImgView: VipHeardImgView = itemView.findViewById(R.id.circle_locus_head)
        val llName: LinearLayout = itemView.findViewById(R.id.ll_name)
        val tvLocusName: TextView = itemView.findViewById(R.id.tv_locus_name)
        val tvLocusTime: TextView = itemView.findViewById(R.id.tv_locus_time)
        val tvLocusTopic: TextView = itemView.findViewById(R.id.tv_locus_topic)
        val mContent: ExpandableTextView = itemView.findViewById(R.id.tv_locus_content)
        val tvLocusAddress: TextView = itemView.findViewById(R.id.tv_locus_address)
        val llTopic: LinearLayout = itemView.findViewById(R.id.ll_topic)
        val tvLocusLikeCount: TextView = itemView.findViewById(R.id.tv_locus_like_count)
        val tvLocusCollectCount: TextView = itemView.findViewById(R.id.tv_locus_collect_count)
        val tvLocusCommentCount: TextView = itemView.findViewById(R.id.tv_locus_comment_count)
        val likeButton: LikeButton = itemView.findViewById(R.id.iv_locus_like)
        val collectButton: LikeButton = itemView.findViewById(R.id.iv_locus_collect)
        val container: FrameLayout = itemView.findViewById(R.id.fl_container)
        val ivLocusShare: ImageView = itemView.findViewById(R.id.iv_locus_share)
        val ivLocusComment: ImageView = itemView.findViewById(R.id.iv_locus_comment)
        val hotCommentsView: HotCommentsView = itemView.findViewById(R.id.hc_comment)
        lateinit var item: FollowDynamicBean.DataBeanX.DataBean
        lateinit var context: Context
        var locusImageView: LocusImageView? = null
        var videoView: LocusVideoView? = null

        @SuppressLint("SetTextI18n")
        fun setUI(context: Context, data: ArrayList<FollowDynamicBean.DataBeanX.DataBean>, position: Int, communityViewModel: CommunityViewModel, mCallback: Callback) {
            item = data[position]
            this.context = context
            vipHeardImgView.setData(item.icon, item.isFans == 1, View.GONE)
            val params: LinearLayout.LayoutParams = llName.layoutParams as LinearLayout.LayoutParams
            if (item.isFans == 1) {
                params.topMargin = ScreenUtils.dpToPx(18)
            } else {
                params.topMargin = ScreenUtils.dpToPx(12)
            }
            llName.layoutParams = params
            tvLocusName.text = item.name
            tvLocusTime.text = TimeUtil.fromToday(item.createTime)

            if (item.tags.checkNotNull()) {
                tvLocusTopic.text = "# ${item.tags[0]}"
                tvLocusTopic.visibility = View.VISIBLE
            } else {
                tvLocusTopic.visibility = View.GONE
            }
            if (item.address.isNullOrEmpty()) {
                tvLocusAddress.visibility = View.GONE
            } else {
                tvLocusAddress.text = item.address
                tvLocusAddress.visibility = View.VISIBLE
            }
            if (item.address.isNullOrEmpty() && item.tags.isNullOrEmpty()) {
                llTopic.visibility = View.GONE
            } else {
                llTopic.visibility = View.VISIBLE
            }
            if (TextUtils.isEmpty(item.content.trim())) {
                mContent.visibility = View.GONE
            } else {
                mContent.visibility = View.VISIBLE
                mContent.setContent(item.content.trim())
            }

            tvLocusLikeCount.text = if (item.supportNum == 0) "点赞" else item.supportNum.toString()
            tvLocusCollectCount.text = if (item.favoriteNum == 0) "收藏" else item.favoriteNum.toString()
            tvLocusCommentCount.text = if (item.commentNum == 0) "抢首评" else item.commentNum.toString()
            likeButton.isLiked = item.isSupported == 1
            collectButton.isLiked = item.isFavorited == 1

            container.removeAllViews()
            if (isImgDynamic(item.showType)) {
                if (item.images != null && item.images.isNotEmpty()) {
                    locusImageView = LocusImageView(context)
                    locusImageView?.setData(context, item.images, item.id.toString())
                    locusImageView?.setOnDoubleClickListener {
                        if (!likeButton.isLiked) likeButton.performClick()
                    }
                    container.addView(locusImageView)
                }
            } else {
                videoView = LocusVideoView(context)
                videoView?.setData(context, item.video, item.cover, item.id, item.uid.toString(), SpanUtils.appendCut(item.content), object : LocusVideoView.OnVoiceClickListener {
                    override fun onVoiceClick(voice: Boolean) {
                        adapter.isVoice = voice
                    }

                })
                videoView?.setOnDoubleClickListener {
                    if (!likeButton.isLiked) likeButton.performClick()
                }
                container.addView(videoView)
            }
            if (item.comments != null && item.comments.isNotEmpty()) {
                hotCommentsView.visibility = View.VISIBLE
                hotCommentsView.setData(context, item.comments)
            } else {
                hotCommentsView.visibility = View.GONE
            }
            val p: LinearLayout.LayoutParams = rootView.layoutParams as LinearLayout.LayoutParams
            if (mContent.visibility == View.GONE && llTopic.visibility == View.GONE && hotCommentsView.visibility == View.GONE) {
                p.bottomMargin = ScreenUtils.dpToPx(4)
            } else if (mContent.visibility == View.VISIBLE && llTopic.visibility == View.GONE && hotCommentsView.visibility == View.GONE) {
                p.bottomMargin = ScreenUtils.dpToPx(0)
            } else {
                p.bottomMargin = ScreenUtils.dpToPx(12)
            }
            rootView.layoutParams = p
            likeButton.setOnLikeListener(object : OnLikeListener {
                override fun liked(likeButton: LikeButton) {
                    likeButton.isEnabled = false
                    doLikeToggle(item, communityViewModel, tvLocusLikeCount, likeButton)
                }

                override fun unLiked(likeButton: LikeButton) {
                    likeButton.isEnabled = false
                    doLikeToggle(item, communityViewModel, tvLocusLikeCount, likeButton)
                }
            })
            collectButton.setOnLikeListener(object : OnLikeListener {
                override fun liked(collectButton: LikeButton) {
                    collectButton.isEnabled = false
                    doCollectToggle(item, communityViewModel, tvLocusCollectCount, collectButton)
                }

                override fun unLiked(collectButton: LikeButton) {
                    doCollectToggle(item, communityViewModel, tvLocusCollectCount, collectButton)
                }
            })
            itemView.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick())
                    return@setOnClickListener
                if (isImgDynamic(item.showType)) {
                    locusImageView?.goImageDetail(item.id.toString())
                } else {
                    videoView?.goVideoDetails(item.id, item.uid.toString())
                }
            }

            tvLocusTopic.setOnClickListener {
                if (item.tagIds.checkNotNull()) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["tid"] = item.tagIds!![0]
                    hashMap["tsource"] = "关注列表"
                    ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL, hashMap)
                }
            }
            vipHeardImgView.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick())
                    goUserHomePage(item.uid.toString())
            }
            tvLocusName.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick())
                    goUserHomePage(item.uid.toString())
            }
            ivLocusShare.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick())
                    mCallback.onClickShare(data.indexOf(item), item)
            }
            hotCommentsView.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick())
                    mCallback.onClickComment(data.indexOf(item), item)
            }
            ivLocusComment.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick())
                    mCallback.onClickComment(data.indexOf(item), item)
            }
        }

        private fun doLikeToggle(item: FollowDynamicBean.DataBeanX.DataBean, communityViewModel: CommunityViewModel, textView: TextView, likeButton: LikeButton) {
            SensorsDataManager.instance.giveLike(item.isSupported == 1, "首页-关注页", "动态外部", SpanUtils.appendCut(item.content))
            communityViewModel.likeAction(item.isSupported != 1, item.id, object : APIResponse<Boolean>(this) {
                override fun onSuccess(result: Boolean, json: String?) {
                    likeButton.isEnabled = true
                    if (result) {
                        item.supportNum = if (item.isSupported == 1) item.supportNum.minus(1) else item.supportNum.plus(1)
                        item.isSupported = if (item.isSupported == 1) 2 else 1
                        textView.text = if (item.supportNum == 0) "点赞" else item.supportNum.toString()
                        likeButton.isLiked = item.isSupported == 1
                    }
                }

                override fun onFailed(message: String?) {
                    likeButton.isEnabled = true
                }
            })
        }

        private fun doCollectToggle(item: FollowDynamicBean.DataBeanX.DataBean, communityViewModel: CommunityViewModel, textView: TextView, likeButton: LikeButton) {
            communityViewModel.collectAction(item.isFavorited != 1, item.id.toLong(), object : APIResponse<Boolean>(this) {
                override fun onSuccess(result: Boolean, json: String?) {
                    if (result) {
                        collectButton.isEnabled = true
                        item.isFavorited == 1
                        item.favoriteNum = if (item.isFavorited == 1) item.favoriteNum.minus(1) else item.favoriteNum.plus(1)
                        item.isFavorited = if (item.isFavorited == 1) 2 else 1
                        textView.text = if (item.favoriteNum == 0) "收藏" else item.favoriteNum.toString()
                        likeButton.isLiked = item.isFavorited == 1
                        ToastUtils.showShort(context, if (item.isFavorited == 1) "收藏成功" else "取消收藏")
                    }
                }

                override fun onFailed(message: String?) {
                    collectButton.isEnabled = true
                }
            })
        }

        private fun isImgDynamic(showType: Int): Boolean {
            return showType == 1
        }


        private fun goUserHomePage(id: String) {
            val hashMap = HashMap<String, Any>()
            hashMap[BaseConstant.USER_ID] = id
            ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
        }

        override fun setActive() {
            if (container.childCount > 0 && container.getChildAt(0) is LocusVideoView) {
                (container.getChildAt(0) as LocusVideoView).isVoice = adapter.isVoice//更新喇叭状态
                (container.getChildAt(0) as LocusVideoView).setActive()
            }
        }

        override fun deactivate() {
            if (container.childCount > 0 && container.getChildAt(0) is LocusVideoView) {
                (container.getChildAt(0) as LocusVideoView).deactivate()
            }
        }

        override fun getAutoplayView(): View? {
            if (container.getChildAt(0) is LocusVideoView) {
                return (container.getChildAt(0) as LocusVideoView).autoplayView
            }
            return null
        }
    }

    class RecommendViewHolder(@NonNull itemView: View) : RecyclerView.ViewHolder(itemView) {
        val viewPager: ViewPager = itemView.findViewById(R.id.vp_recommend_users)
        val tvLocusTime: TextView = itemView.findViewById(R.id.tv_locus_time)
        val tvLocusTitle: TextView = itemView.findViewById(R.id.tv_locus_title)
        val topView: View = itemView.findViewById(R.id.view_top)
        val bottomView: View = itemView.findViewById(R.id.view_bottom)
    }

    class InterestViewHolder(@NonNull itemView: View, context: Context, viewModel: CommunityViewModel) : RecyclerView.ViewHolder(itemView) {
        val recyclerView: RecyclerView = itemView.findViewById(R.id.rv_interest_users)
    }

    class UserListViewHolder(@NonNull itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mRvFollow: RecyclerView = itemView.findViewById(R.id.rv_community_follow)
        fun setUI(item: FollowDynamicBean.DataBeanX.DataBean) {
            val followAdapter = FollowUsersAdapter()
            mRvFollow.adapter = followAdapter
            followAdapter.setNewData(item.followUsersBeanItems)
        }

    }
}